package com.usian.wemedia.service.impl

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.usian.model.base.BaseServiceImpl
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.media.dtos.WmNewsDto
import com.usian.model.media.dtos.WmNewsPageReqDto
import com.usian.model.media.pojos.WmNews
import com.usian.model.media.pojos.WmNews.Status.PUBLISHED
import com.usian.model.media.pojos.WmNewsMaterial
import com.usian.utils.threadlocal.UserIdThreadLocalUtils
import com.usian.wemedia.constants.WemediaContans
import com.usian.wemedia.mapper.WmMaterialMapper
import com.usian.wemedia.mapper.WmNewsMapper
import com.usian.wemedia.mapper.WmNewsMaterialMapper
import com.usian.wemedia.service.WmNewsServiceKt
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
import kotlin.collections.ArrayList

@Service
open class WmNewsServiceImplKt : WmNewsServiceKt, BaseServiceImpl<WmNewsMapper, WmNews>() {

    @Value("\${file.url}")
    var fileurl: String? = null


    @Autowired
    lateinit var wmNewsMaterialMapper: WmNewsMaterialMapper

    @Autowired
    lateinit var wmMaterialMapper: WmMaterialMapper

    override fun findAll(dto: WmNewsPageReqDto?): ResponseResult<*> {
        dto ?: return errorParam
        val userId = UserIdThreadLocalUtils.getUserId() ?: return needLogin
        val wapper = LambdaQueryWrapper<WmNews>()
        val w = wapper.eq({ obj: WmNews -> obj.userId }, userId)
            .eq(dto.status != null, WmNews::getStatus, dto.status)
            .eq(dto.channelId != null, WmNews::getChannelId, dto.channelId)
            .like(dto.keyword != null, WmNews::getTitle, dto.keyword).between(
                dto.beginPubDate != null && dto.endPubDate != null, WmNews::getPublishTime,
                dto.beginPubDate, dto.endPubDate
            ).orderByDesc(WmNews::getCreatedTime)

        val pageData = getPageData(dto, w)

        pageData.host = fileurl
        return pageData
    }

    override fun submitNews(dto: WmNewsDto?): ResponseResult<*> {
        dto ?: return errorParam
        val userId = UserIdThreadLocalUtils.getUserId() ?: return needLogin
        var wmNews = WmNews()
        BeanUtils.copyProperties(wmNews, dto)
//        wmNews.also {dto.run { it.id=id it.userId=userId it.channelId=channelId it.enable=enable it.status=status it.title=title it.type=type it.content=content it.labels=labels it.submitedTime= Date() it.publishTime=publishTime } }
        wmNews.userId = userId

        //获取内容中素材
        val content = wmNews.content
        var contentImages = ArrayList<String>()
        for (any in JSONArray.parseArray(content)) {
            val array = JSONObject.parseObject(any.toString() as String?)
            if (array.getString("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                contentImages.add(array.getString("value").replace(fileurl.toString(), ""))
            }
        }

        //id为空添加，不为空修改
        if (wmNews.id == null) {
            //添加创建时间
            wmNews.createdTime = Date()

            //根据type类型状态确定封面图格式及内容
            typeOrImage(dto, wmNews, contentImages)

            save(wmNews)
            val wmNewsId = wmNews.id
            //获取封面图url对应字符串集合
            val images = wmNews.images.split(",")
            //保存封面图关联关系
            putWmNewsMaterial(images, wmNewsId, WemediaContans.WM_COVER_REFERENCE)

            //保存内容图关联关系
            putWmNewsMaterial(contentImages, wmNewsId, WemediaContans.WM_CONTENT_REFERENCE)

        } else {
            getById(dto.id) ?: return ResponseResult.errorResult(1001, "文章不存在")
            //更新提交时间
            wmNews.submitedTime = Date()
            //根据type类型状态确定封面图格式及内容
            typeOrImage(dto, wmNews, contentImages)

            //根据wmNews的id删除关联关系
            wmNewsMaterialMapper.deleteByNewsId(wmNews.id)

            updateById(wmNews)

            val images = wmNews.images.split(",")
            //保存封面图关联关系
            putWmNewsMaterial(images, wmNews.id, WemediaContans.WM_COVER_REFERENCE)

            //保存内容图关联关系
            putWmNewsMaterial(contentImages, wmNews.id, WemediaContans.WM_CONTENT_REFERENCE)
        }
        return success


    }

    private fun putWmNewsMaterial(
        images: List<String>,
        wmNewsId: Int?,
        type: Short?
    ) {
        var list = ArrayList<String>()
        images.forEach { s: String ->
            val materialId = wmMaterialMapper.findByUrl(s)
            list.add(materialId.toString())
        }
        wmNewsMaterialMapper.saveRelations(list, wmNewsId, type);
    }

    private fun typeOrImage(dto: WmNewsDto, wmNews: WmNews, images: ArrayList<String>) {
        val image = StringBuilder("")
        if (dto.type.equals(WemediaContans.WM_NEWS_AUTO_TYPE)) {
            wmNews.type = (if (images.size < 1) 0 else if (images.size > 2) 3 else 1).toShort()
            if (images.size < 1) {
                wmNews.type = 0
                wmNews.images = null
            } else if (images.size > 2) {
                wmNews.type = 3
                wmNews.images = images[0] + "," + images[1] + "," + images[2]
            } else {
                wmNews.type = 1
                wmNews.images = images[0]
            }
        } else {
            val size = dto.images.size
            for (i in 0 until size) {
                if (i == size - 1) {
                    image.append(dto.images[i].replace(fileurl.toString(), ""))
                } else {
                    image.append(dto.images[i].replace(fileurl.toString(), "")).append(",")
                }
            }
            wmNews.images = image.toString()
        }
    }

    override fun findWmNewsById(id: Int?): ResponseResult<*> {
        id ?: return errorParam
        val wmNews = getById(id)
        wmNews ?: return ResponseResult.errorResult(1002, "文章不存在")
        return ResponseResult.okResult(wmNews)
    }


    @Transactional
    override fun delNews(id: Int?): ResponseResult<*> {
        if (id == null) return errorParam
        val news = getById(id)
        news ?: return ResponseResult.errorResult(1002, "文章不存在")
        if (news.status.equals(PUBLISHED) && news.enable.equals(1))
            return ResponseResult.errorResult(1003, "文章已发布上架，不能删除")
        wmNewsMaterialMapper.deleteByNewsId(id)
        removeById(id)
        return success
    }

    override fun downOrUp(dto: WmNewsDto?): ResponseResult<*> {
        dto ?: return errorParam
        val wmNews = getById(dto.id ?: return errorParam) ?: return ResponseResult.errorResult(1002, "文章不存在")
        if (!wmNews.status.equals(PUBLISHED)) return ResponseResult.errorResult(1003, "文章未发布，不能上架")
        update(Wrappers.lambdaUpdate<WmNews?>().eq(WmNews::getId, dto.id).set(WmNews::getEnable, dto.enable))
        return success
    }


}

